import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { visualizer } from 'rollup-plugin-visualizer'
// 自动导入配置

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

// EP自动导入

import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'

// 整合SVG图标
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

// 整合UnoCSS
import UnoCSS from 'unocss/vite'

// 代码压缩
import viteCompression from 'vite-plugin-compression2'

import path from 'path'
const pathSrc = path.resolve(__dirname, 'src')

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  return {
    css: {
      devSourcemap: true,
      // CSS 预处理器
      preprocessorOptions: {
        //define global scss variable
        scss: {
          javascriptEnabled: true,
          additionalData: `@use "@cwpf/layout/styles/variables.scss" as *;`
        }
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      UnoCSS({
        /* options */
      }),
      AutoImport({
        // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        imports: ['vue', '@vueuse/core', 'vue-router', 'pinia'],
        eslintrc: {
          enabled: true, // 是否自动生成 eslint 规则，建议生成之后设置 false
          filepath: './.eslintrc-auto-import.json' // 指定自动导入函数 eslint 规则的文件
        },
        resolvers: [
          // 自动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox... (带样式)
          ElementPlusResolver(),
          // 自动导入图标组件
          IconsResolver({})
        ],
        vueTemplate: true, // 是否在 vue 模板中自动导入
        dts: path.resolve(pathSrc, 'types', 'auto-imports.d.ts') // 指定自动导入函数TS类型声明文件路径
      }),
      Components({
        resolvers: [
          // 自动导入 Element Plus 组件
          ElementPlusResolver(),
          // 自动注册图标组件
          IconsResolver({
            prefix: 'icon',
            enabledCollections: ['ep'] // element-plus图标库，其他图标库 https://icon-sets.iconify.design/
          })
        ],
        dts: path.resolve(pathSrc, 'types', 'components.d.ts') // 指定自动导入组件TS类型声明文件路径
      }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [
          path.resolve(process.cwd(), 'src/assets/icons'),
          // 获取单仓库其他包的绝对路径
          path.resolve(path.resolve(process.cwd(), '..'), 'components/src/SvgIcon/icons')
        ],
        // 指定symbolId格式
        symbolId: `icon-${env.VITE_ICON_LOCAL}-[dir]-[name]`
      }),
      Icons({
        // 自动安装图标库
        autoInstall: true
      }),
      // 打包压缩
      viteCompression(),
      // 打包分析
      visualizer()
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: (id: string) => {
            if (['vue', 'vue-router', 'pinia'].includes(id)) {
              return 'vue'
            }
            if (id.includes('@vueuse/')) {
              return '@vueuse'
            }
            if (id.includes('echarts')) {
              return 'echarts'
            }
            if (id.includes('axios')) {
              return 'axios'
            }
            if (id.includes('@wangeditor/')) {
              return '@wangeditor'
            }
            if (id.includes('@antv/')) {
              return '@antv'
            }
            if (id.includes('@element-plus/')) {
              return '@element-plus'
            }
          }
        }
      }
    },
    // 开发服务器
    server: {
      port: 8888,
      cors: true,
      host: '0.0.0.0',
      proxy: {
        '/dev': {
          target: 'http://127.0.0.1:8080',
          changeOrigin: false,
          ws: false,
          rewrite: (path) => path.replace(/^\/dev/, '')
        }
      }
    },
    // 预览服务器
    preview: {
      port: 9000,
      cors: true,
      host: '0.0.0.0',
      proxy: {
        '/dev': {
          target: 'http://127.0.0.1:8080',
          changeOrigin: false,
          ws: false,
          rewrite: (path) => path.replace(/^\/dev/, '')
        }
      }
    }
  }
})
